package wwl.lsf;

/**
 * @Title
 * @Author wangwenliang
 * @Date 2021/3/29
 * @Description
 */
public class 颠倒二进制位 {
    public static void main(String[] args) {
        int a = 4;
        System.out.println("reverseBits(1) = " + reverseBits(a));
        System.out.println("zijifanzhuan(1) = " + zijifanzhuan(a));

    }

    public static int zijifanzhuan(int i) {
        int ret = 0;

        for (int j = 0; j < 32 && i != 0; j++) {
            //取出转入的最低位
            int low1bit = i & 1;
            //移动这个位到相应的翻转位置
            ret |= low1bit << 31 - j;
            //将下一个需要翻转的位值移动到最低位
            i >>>= 1;

        }

        return ret;

    }


    public static int reverseBits(int n) {
        int rev = 0;
        for (int i = 0; i < 32 && n != 0; ++i) {
            rev |= (n & 1) << (31 - i);
            n >>>= 1;
        }
        return rev;
    }
}
